package com.sxkf.template.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.template.entity.PostLike;
import com.sxkf.template.entity.PostNotice;
import com.sxkf.template.mapper.PostLikeMapper;
import com.sxkf.template.mapper.PostMapper;
import com.sxkf.template.mapper.PostNoticeMapper;
import com.sxkf.template.service.PostLikeService;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 帖子点赞 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-08-20 11:48:57
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PostLikeServiceImpl extends ServiceImpl<PostLikeMapper, PostLike> implements PostLikeService {
    @Resource
    private PostNoticeMapper postNoticeMapper;
    @Resource
    private PostMapper postMapper;

    @Override
    public Boolean add(PostLike postLike) {
        PostLike one = getOne(new LambdaQueryWrapper<PostLike>().eq(PostLike::getPostId, postLike.getPostId()).eq(PostLike::getUserId, postLike.getUserId()));
        //如果已有点赞记录则取消点赞
        if (one != null){
            removeById(one);
            postMapper.reduceLikeCount(postLike.getPostId());
            return false;
        }

        //如果未点赞则进行点赞
        save(postLike);

        //帖子点赞量+1
        postMapper.addLikeCount(postLike.getPostId());

        //添加消息通知
        PostNotice postNotice = new PostNotice();
        postNotice.setPostId(postLike.getPostId());
        postNotice.setUserId(postLike.getUserId());
        postNotice.setType("1");
        postNotice.setState("0");
        String pictureJson = postMapper.selectById(postLike.getPostId()).getPictureJson();
        if (CheckEmptyUtil.isNotEmpty(pictureJson)){
            String[] pics = pictureJson.split(",");
            postNotice.setPostPicture(pics[0]);
//            List<String> pics = JSON.parseArray(pictureJson, String.class);
//            if (!pics.isEmpty()){
//                postNotice.setPostPicture(pics.get(0));
//            }
        }
        postNoticeMapper.insert(postNotice);
        return true;
    }

    @Override
    public Boolean isAdd(String userId, String postId) {

        PostLike one = getOne(new LambdaQueryWrapper<PostLike>()
                .eq(PostLike::getPostId, postId)
                .eq(PostLike::getUserId, userId));


        return !CheckEmptyUtil.isEmpty(one);
    }
}
